<template>
    <div style="background-color: white">
        <div class="custom-tree-container" style="width: 60%">
            <!--
            :props="{
                      children: 'children',   装子节点的是children集合
                      label: 'name',   我们的分类对象中name就是要显示的标签名称
                    }"

            :node-key="id"  节点的唯一标记
            :expand-on-click-node="false"  点击节点展开 设置为false  只有点击箭头才会展开
            -->
            <el-tree
                    :props="{
                      children: 'children',
                      label: 'name',
                    }"
                    :node-key="id"
                    :data="data"
                    show-checkbox
                    @check-change="handleCheckChange"
                    :expand-on-click-node="false"
            >
                <template #default="{ node, data }">
                    <span class="custom-tree-node">
                        <!-- 显示出来的类型名称 -->
                      <span>{{ node.label }}</span>
                      <span>
                          <!-- 切换状态的按钮
                             切换状态会调用changeState方法
                          -->
                          <el-switch
                                  v-model="data.state"
                                  size="small"
                                  :active-value="1"
                                  :inactive-value="0"
                                  @change="changeState(data)"
                          />
                      </span>
                      <span>
                          <!-- 编辑节点  只能编辑名称 -->
                        <el-button  size="mini"  @click="editNode(data)"> Edit </el-button>
                        <el-button v-if="node.level!=3"  size="mini"  @click="append(data)"> Append </el-button>
                        <el-button v-if="!data.children" style="margin-right: 8px"  size="mini" @click="remove(node, data)"> Delete </el-button>
                      </span>
                    </span>
                </template>
            </el-tree>

        </div>

        <!-- 编辑弹出框 -->
        <el-dialog title="编辑类别信息" v-model="editVisible" width="30%">
            <el-form ref="form" :model="form" label-width="70px">
                <el-form-item label="名称">
                    <el-input v-model="form.name"></el-input>
                </el-form-item>
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="editVisible = false">取 消</el-button>
                    <el-button type="primary" @click="saveEdit">确 定</el-button>
                </span>
            </template>
        </el-dialog>

    </div>
</template>

<script>
export default {
    name: "Category",
    data() {
        return {
            currentData: null,
            editVisible: false,
            data: [],
            form: {
                name: '',
            },
            what: 'save'
        };
    },
    mounted() {
        this.getTreeData();
    },
    methods: {
        //***********弹出对话框  进行编辑操作*****************
        editNode(data){
            this.what = 'update';
            this.editVisible = true;
            this.currentData = data;
            this.form = {
                id: data.id,
                name: data.name
            }
        },
        //******************修改节点状态********************
        changeState(data){
            console.log("data--------",data);

            if (data.level!=3){
                this.$confirm("确定要更新状态吗，这将会更新所有子类别的状态？", "提示", {
                    type: "warning"
                })
                .then(() => {
                    this.handleChangeState(data);
                })
                .catch(() => {
                    data.state = (data.state==0?1:0)
                });
            }else{
                this.handleChangeState(data);
            }

        },
        //****************发送更新状态的请求*****************
        handleChangeState(data){
            this.$axios({
                method: 'post',
                url: '/category/changeState',
                data: data
            }).then(res=>{
                if(!res || res.data.code!=200){
                    this.$message.error(res.data.msg || '更新状态失败');
                    data.state = (data.state==0?1:0)
                    return;
                }
                this.$message.success('更新成功');
                //更新页面节点状态
                if(data.children){
                    data.children.forEach(child=>{
                        child.state = data.state
                        if (child.children){
                            child.children.forEach(c=>{
                                c.state = data.state;
                            })
                        }
                    })
                }
            }).catch(error=>{
                data.state = (data.state==0?1:0)
                this.$message.error(error.message);
            })
        },
        //***************只有没有子节点的才能删除****************
        remove(node,data){
            console.log(node,data);
            // 二次确认删除
            this.$confirm("确定要删除吗？", "提示", {
                type: "warning"
            })
            .then(() => {
                //确定删除之后发送删除请求
                this.$axios({
                    method:'delete',
                    url:'/category/'+node.data.id
                }).then(res=>{
                    if(res && res.data.code==200){
                        this.$message.success("删除成功");
                        //从页面节点上移除要删除的节点
                        const parent = node.parent
                        const children = parent.data.children
                        const index = children.findIndex((d) => d.id === data.id)
                        children.splice(index, 1)
                    }else{
                        this.$message.error("删除失败，请重试");
                    }
                }).catch(error=>{
                    this.$message.error(error.message);
                })
            })
            .catch(() => {});
        },
        //***************添加或修改操作***针对节点名称****************
        saveEdit(){
            if (this.what == 'save'){
                this.save();
            }else if (this.what == 'update'){
                this.update();
            }
        },
        //*************修改的方法****************
        update(){
            this.$axios({
                method: 'post',
                url: '/category',
                data: this.form
            }).then(res=>{
                console.log('修改节点完成----------',res);
                if (res && res.data.code==200){
                    //更新页面的节点
                    this.currentData.name = this.form.name;
                }else{
                    this.$message.error(res.data.msg||'修改节点名称失败');
                }
                this.editVisible = false;
            }).catch(error=>{
                this.$message.error(error.message);
            })
        },
        //*************添加节点****************
        save(){
            this.$axios({
                method: 'post',
                url: '/category',
                data: {
                    name: this.form.name,
                    parentId: this.currentData.id,   //当前操作节点的ID值
                    level: this.currentData.level+1,  //当前操作节点的level+1
                    sort: 0,
                    state: 1
                }
            }).then(res=>{
                console.log('添加节点完成----------',res);
                if (res && res.data.code==200){
                    // const newChild = { id: id++, label: 'testtest', children: [] }
                    //添加节点完成  更新节点
                    if (!this.currentData.children) {
                        this.currentData.children = []
                    }
                    //给当前操作节点添加子节点
                    this.currentData.children.push(res.data.data);
                    //对话框隐藏
                    this.editVisible = false;
                }
            }).catch(error=>{
                this.$message.error(error.message);
            })
        },
        //********编辑名称的对话框显示**********
        append(data){
            this.what = 'save';
            this.currentData = data;
            this.editVisible = true;
            this.form = {
                name:''
            }
        },
        //**************获取树结构的商品类型***************
        getTreeData(){
            this.$axios({
                method: 'get',
                url: '/category/tree'
            }).then(res=>{
                if (res && res.data.code == 200){
                    this.data = res.data.data
                }else{
                    this.$message.error('查询商品类别失败');
                }
            }).catch(error=>{
                this.$message.error(error.message);
            })
        },
        handleCheckChange(data, checked, indeterminate){
            console.log(data, checked, indeterminate)
        }
    }
};
</script>

<style scoped>
    .custom-tree-node {
        flex: 1;
        display: flex;
        align-items: center;
        justify-content: space-between;
        font-size: 14px;
        padding-right: 8px;
    }
</style>
